/*
 * @Author: shawnxiao
 * @Date: 2021-04-27 14:16:13
 * @LastEditTime: 2021-04-27 15:11:05
 * @FilePath: /react-ts-webpack/src/components/TableCom/index.tsx
 */
import React, {createElement, useState, useImperativeHandle} from 'react'
import { Link } from 'react-router-dom'
import { Table } from 'antd'
const h = createElement
import {currency, timestampToTime} from '@/common/utils'

const TableCom = ({columns, dataSource, hasCheck, cRef, getCheckboxProps, bordered}:any) => {
  const empty = '-',
    [selectedRowKeys, setSelectedRowKeys ] = useState([]),
    [selectedRows, setSelectedRows] = useState([]),
    render = {
      Default: (v:any) => v,
      Enum: (v:any, {Enum}:any) => {
        if (!Enum[v]) return empty
        return Enum[v]
      },
      Format: (v:any, {format}:any, row:any) => format(v, row),
      // eslint-disable-next-line no-undef
      Currency: (v:any) => currency(v),
      Date: (v:any) => timestampToTime(v, 'second'),
      // eslint-disable-next-line react/display-name
      Link: (v:any, {url}:any) => <Link to={url}>{v}</Link>,
      Action: (v:any, {value}:any, row:any) => {
        const result = value.filter((n:any) => {
          const {filter = () => true} = n
          return filter(row)
        })
        return result.map((t:any) => <span className="table-link" onClick={() => t.click(row)} key={t.label}>{t.label}</span>)
      }
    }

  columns = columns.map((n:any) => {
    const { type = 'Default', merge } = n
    return {...n, render: (v:any, row:any, index:any) => (!v || v.length < 1) && type !== 'Action' ? empty : merge && typeof merge === 'function' ? merge(render[type](v, n, row), index) : render[type](v, n, row)}
  })

  // 父组件获取selectedRowKeys的方法-cRef就是父组件传过来的ref
  useImperativeHandle(cRef, () => ({
    // getSelectedRowKeys就是暴露给父组件的方法
    getSelectedRowKeys: () => selectedRowKeys,
    getSelectedRows: () => selectedRows
  }))

  const onSelectChange = (selectedRowKeys:any, selectedRows:any) => {
    setSelectedRowKeys(selectedRowKeys)
    setSelectedRows(selectedRows)
  }

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
    getCheckboxProps: (record:any) => getCheckboxProps(record)
  }

  return hasCheck ? h(Table, {columns, dataSource, rowSelection, bordered}) : h(Table, {columns, dataSource, bordered})
}

export default TableCom
